package com.yuzhitong.shapi.presenter;

import com.alibaba.fastjson.JSON;
import a.a.a.MyApplication;
import com.yuzhitong.shapi.base.BasePresenter;
import com.yuzhitong.shapi.base.Contents;
import com.yuzhitong.shapi.base.net.BaseListBean;
import com.yuzhitong.shapi.base.net.BaseObjectBean;
import com.yuzhitong.shapi.bean.CategoryBean;
import com.yuzhitong.shapi.bean.PlayAddressBean;
import com.yuzhitong.shapi.contract.MovieContract;
import com.yuzhitong.shapi.model.MovieModel;
import com.yuzhitong.shapi.net.MyObserver;
import com.yuzhitong.shapi.net.RxScheduler;
import com.yuzhitong.shapi.util.StringUtil;

import java.util.List;

import io.reactivex.rxjava3.annotations.NonNull;

/**
 * Created by Brsya
 * CreateDate: 2022/5/8  15:01
 * Description:
 * 影视
 */
public class MoviePresenter extends BasePresenter<MovieContract.View> implements MovieContract.Presenter {

    private MovieContract.Model model;

    public MoviePresenter() {
        model = new MovieModel();
    }

    @Override
    public void getCategory() {
        try {
            String category = MyApplication.aCache.getAsString(Contents.CACHE_KEY_CATEGORY);
            if (!StringUtil.isEmpty(category)) {
                List<CategoryBean> categoryBeans = JSON.parseArray(category, CategoryBean.class);
                mView.showCategory(categoryBeans);
                return;
            }
        } catch (Exception e) {
            // 解析失败不做处理,继续请求网络数据
        }

        mView.showLoading();

        model.getCategory(getPublicPar())
                .compose(RxScheduler.Obs_io_main())
                .to(mView.bindAutoDispose())
                .subscribe(new MyObserver<BaseListBean<CategoryBean>>(mView) {
                    @Override
                    public void success(@NonNull BaseListBean<CategoryBean> baseBean) {
                        baseBean.handleData(CategoryBean.class);
                        if (baseBean.getData() != null && baseBean.getData().size() > 0) {
                            mView.showCategory(baseBean.getData());
                            MyApplication.aCache.put(Contents.CACHE_KEY_CATEGORY, JSON.toJSONString(baseBean.getData()));
                        }
                    }
                });
    }

    @Override
    public void getPlayAddressNew() {
        model.getPlayAddressNew(getPublicPar())
                .compose(RxScheduler.Obs_io_main())
                .to(mView.bindAutoDispose())
                .subscribe(new MyObserver<BaseObjectBean<PlayAddressBean>>(mView) {
                    @Override
                    public void success(@NonNull BaseObjectBean<PlayAddressBean> baseBean) {
                        baseBean.handleData(PlayAddressBean.class);
                        MyApplication.playAddressBean = baseBean.getData();
                    }
                });
    }
}
